/*
 * @Author: LiZhiWei
 * @Date: 2025-07-28 11:47:24
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 11:51:15
 * @Description: 恢复数据 Hook - 业务逻辑直接写入函数体
 */
import { api, Http } from '#/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export function useRestore(
  options: {
    entity?: string
    list?: Ref<any[]>
    message?: string
  } = {
    entity: '',
    message: '恢复成功',
  }
) {
  const { entity = '', list, message } = options
  const formLoading = ref(false)

  function restore(url: string, data: any, tip = '确定恢复所选数据吗？') {
    if (formLoading.value) return Promise.reject(new Error('操作进行中'))
    formLoading.value = true

    return ElMessageBox.confirm(tip, '温馨提示', { type: 'warning' })
      .then(() => {
        return Http.Post(url, { ...data, _method: 'PATCH' })
          .then((res: any) => {
            ElMessage({ type: 'success', message: message ?? '恢复成功' })
            return res
          })
          .finally(() => {
            formLoading.value = false
          })
      })
      .catch(() => {
        formLoading.value = false
        throw new Error('操作已取消')
      })
  }

  const afterRestored = (ids: (number | string)[], res: any, onRestored?: (res: any) => void) => {
    if (list?.value) {
      list.value = list.value.filter((row) => !ids.includes(row.id))
    }

    onRestored && onRestored(res)
  }

  const handleRestore = (id: number | string, onRestored?: (res: any) => void) => {
    restore(api[entity].restoreBatch, { ids: [id] }).then((res) => {
      afterRestored([id], res, onRestored)
    })
  }

  const handleRestoreWith = (url: RequestUrl, onRestored?: (res: any) => void) => {
    restore(url.restore as string, url.params).then((res) => {
      afterRestored(url.params?.ids, res, onRestored)
    })
  }

  const handleRestoreBatch = (ids: Array<number | string>, onRestored?: (res: any) => void) => {
    restore(api[entity].restoreBatch, { ids }, `确定恢复选中的 ${ids.length} 条数据吗？`).then(
      (res) => {
        afterRestored(ids, res, onRestored)
      }
    )
  }

  const handleRestoreBatchWith = (url: RequestUrl, onRestored?: (res: any) => void) => {
    restore(
      url.restoreBatch as string,
      url.params,
      `确定恢复选中的 ${url.params?.ids.length} 条数据吗？`
    ).then((res) => {
      afterRestored(url.params?.ids, res, onRestored)
    })
  }

  return {
    handleRestore,
    handleRestoreWith,
    handleRestoreBatch,
    handleRestoreBatchWith,
  }
}
